
from django.contrib.auth import login, logout, authenticate
from django.db import DatabaseError
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.http import HttpResponseForbidden
import re,json

# Create your views here.
from django.urls import reverse
from django.views import View

from .models import Users
from mg.utils.exceptions import Forbbiden


class RegisterView(View):
    def get(self,request):
        return render(request,'userapp/register.html')
    def post(self,request):
        # 接收请求参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        phone = request.POST.get("phone")
        
        # 校验参数
        # 判断参数是否⻬全
        if not all([username, password, phone]):
            raise Forbbiden('缺少必传参数')
        # 判断⽤户名是否是5-8个字符
        if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$', username):
            raise Forbbiden('请输⼊5-8个字符的⽤户名')
        # 判断密码是否是3-8个字符
        if not re.match(r'^[0-9a-zA-Z]{3,8}$', password):
            raise Forbbiden('请输⼊3-8位的密码')
        # 判断⼿机号是否合法
        if not re.match(r'^1[35789]\d{9}$', phone):
            raise Forbbiden('请输⼊正确的⼿机号码')
            
        # 保存注册数据
        try:
            user = Users.objects.create_user(username=username,password=password,phone=phone)
        except DatabaseError:
            return render(request,'userapp/register.html',{'reg_error_msg':'注册失败'})
        
        # 状态保持
        login(request,user)
        
        print("session")

        # 返回响应结果
        return redirect(reverse('newsapp:index'))


class UserCountView(View):
    def get(self,request,username):
        '''
        查询当前用户名的记录数
        :param request:
        :param username:
        :return:
        '''
        
        count = Users.objects.filter(username=username).count()
        
        return JsonResponse({'count':count,'code':200,'errormsg':'OK'})


class LogouView(View):
    def get(self,request):
        '''
        用户退出功能
        :param request:
        :return:
        '''
        
        logout(request)
        return redirect(reverse('newsapp:index'))


class PhoneCountView(View):
    def get(self,request,phone):
        '''
        查询手机号的记录数
        :param request:
        :param phone:
        :return:
        '''
        count = Users.objects.filter(phone=phone).count()

        return JsonResponse({'count': count, 'code': 200, 'errormsg': 'OK'})

# 用户名登陆视图
class LoginView(View):
    def get(self,request):
        '''
        显示登陆首页
        :param request:
        :return:
        '''
        next = request.GET.get('next', '')

        return render(request,'userapp/login.html',{'next':next})
    
    def post(self,request):
        '''
        处理登陆请求
        :param request:
        :return:
        '''
     
        # 1、接收参数
        username = request.POST.get('username','')
        password = request.POST.get('password', '')
        remember = request.POST.get('remember', '')

        next = request.POST.get('next', '')

        # 2、校验参数
        if not all([username,password,remember]):
            return HttpResponseForbidden('缺少必传参数')
        
        # 判断⽤户名是否是5-8个字符
        # if not re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,7}$', username):
        #     return HttpResponseForbidden('请输⼊5-8个字符的⽤户名')

        # 判断密码是否是3-8个字符
        if not re.match(r'^[0-9a-zA-Z]{3,8}$', password):
            return HttpResponseForbidden('请输⼊3-8位的密码')
        
        # 3、认证参数是否准确
        user = authenticate(username=username,password=password)
        
        if user is None:
            return render(request,'userapp/login.html',{'login_error':'用户名或密码错误'})
        # 4、状态保持
        login(request,user)
        
        if remember !='on':
            # 没有记住用户，浏览器会话结束就过期
            request.session.set_expiry(0)
        else:
            # 默认两周
            request.session.set_expiry(None)

        if next:
            return redirect(next)
            
        # 5、响应结果
        return redirect(reverse('newsapp:index'))


class UserCenterView(View):
   def get(self,request):
       '''
       显示用户中心页面
       :param request:
       :return:
       '''

       # login_required 这个装饰器已经处理好了
       return render(request, 'userapp/user_center.html')

       # try:
       #     flag = request.user.is_authenticated()
       #     # print(flag)
       #     # 判断当前访客是否已登录
       #     if flag and flag != None:
       #         return render(request, 'userapp/user_center.html')
       # except:
       #
       #     pass
       # # 未登陆，则返回这个
       # return redirect(reverse('newsapp:index'))


class EmailView(View):
    def post(self,request):

        # 接收请求参数
        data = request.body.decode()

        if data:
            d = json.loads(data)

            count = Users.objects.filter(id=d['userid']).update(email=d['email'])

            if count:
                return JsonResponse({'code': 200, 'errormsg':'OK'})

        return JsonResponse({'code': 500, 'errormsg': '格式不正确，保存邮箱失败！'})